import java.util.Arrays;

public class LeetCode1838 {

    public static void main(String[] args) {
        int[] nums = {1, 2, 4};
        int k = 5;

        System.out.println(maxFrequency(nums, k));
    }

    public static int maxFrequency(int[] nums, int k) {
        Arrays.sort(nums);
        int n = nums.length;
        long total = 0;
        int left = 0, res = 1;
        for (int right = 1; right < n; right++) {
            total += (long) (nums[right] - nums[right - 1]) * (right - left);
            while (total > k) {
                total -= nums[right] - nums[left];
                left++;
            }
            res = Math.max(res, right - left + 1);
        }
        return res;
    }

}
